package com.pds.web.company.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.common.core.domain.entity.SysDept;
import com.pds.common.core.domain.entity.SysUser;
import com.pds.common.utils.DateUtils;
import com.pds.common.utils.SecurityUtils;
import com.pds.common.utils.StringUtils;
import com.pds.system.domain.SysUserRole;
import com.pds.system.mapper.SysConfigMapper;
import com.pds.system.mapper.SysRoleMapper;
import com.pds.system.mapper.SysUserMapper;
import com.pds.system.mapper.SysUserRoleMapper;
import com.pds.utils.IdCardUtil;
import com.pds.web.company.domain.PdsCompanyContact;
import com.pds.web.company.excel.CompanyContactExcel;
import com.pds.web.company.mapper.PdsCompanyContactMapper;
import com.pds.web.company.mapper.PdsCompanyInfoMapper;
import com.pds.web.company.service.IPdsCompanyContactService;
import com.pds.web.opsOrganization.domain.OpsOrganizationInfo;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class PdsCompanyContactServiceImpl extends ServiceImpl<PdsCompanyContactMapper, PdsCompanyContact> implements IPdsCompanyContactService {

    @Resource
    private PdsCompanyContactMapper pdsCompanyContactMapper;
    @Resource
    private PdsCompanyInfoMapper pdsCompanyInfoMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysConfigMapper sysConfigMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;

    /**
     * 企业管理员角色键值
     */
    private static final String COMPANY_ADMIN_ROLE_KEY = "enAdmin";

    /**
     * 新增用户
     *
     * @param pdsCompanyContact
     * @return
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void addContact(PdsCompanyContact pdsCompanyContact) throws Exception {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        String createBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        //新增前的容错检查
        if (StringUtils.isEmpty(pdsCompanyContact.getName())) {
            throw new Exception("姓名不能为空");
        }
        if (StringUtils.isEmpty(pdsCompanyContact.getPhone())) {
            throw new Exception("手机号不能为空");
        }
        if(!IdCardUtil.check(pdsCompanyContact.getIdCard())){
            throw new Exception("身份证号不正确，请核实");
        }
        if (sysUserMapper.selectUserByUserName(pdsCompanyContact.getPhone()) != null) {
            throw new Exception("用户已存在，请核实！");
        }

        //1.在pds_company_contact表中插入数据
        pdsCompanyContact.setCompanyId(pdsCompanyInfoMapper.getIdByDeptId(deptId));
        pdsCompanyContact.setStatus("0");
        pdsCompanyContact.setCreateBy(createBy);
        pdsCompanyContact.setCreateTime(date);
        pdsCompanyContactMapper.insert(pdsCompanyContact);

        //2.在sys_user表中插入数据
        SysUser user = new SysUser();
        user.setDeptId(deptId);
        user.setUserName(pdsCompanyContact.getPhone());
        user.setNickName(pdsCompanyContact.getName());
        user.setPhonenumber(pdsCompanyContact.getPhone());
        user.setSex(pdsCompanyContact.getSex());
        String initPassword = sysConfigMapper.selectInitPassword();
        user.setPassword(SecurityUtils.encryptPassword(initPassword));
        user.setCreateBy(createBy);
        user.setRemark(pdsCompanyContact.getRemark());
        sysUserMapper.insertUser(user);

        //3.将userId更新到pds_company_contact表中
        pdsCompanyContact.setUserId(user.getUserId());
        pdsCompanyContactMapper.updateById(pdsCompanyContact);

        //4.在sys_user_role表中添加数据
        List<SysUserRole> userRoleList = new ArrayList<>();
        String[] roleIds = pdsCompanyContact.getRoleIds().split(",");
        for (String id : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(user.getUserId());
            userRole.setRoleId(Long.parseLong(id));
            userRoleList.add(userRole);
        }
        sysUserRoleMapper.batchUserRole(userRoleList);
    }

    /**
     * 修改用户
     *
     * @param pdsCompanyContact
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void updateContact(PdsCompanyContact pdsCompanyContact) throws Exception {
        Long deptId = SecurityUtils.getLoginUser().getUser().getDeptId();
        String updateBy = SecurityUtils.getLoginUser().getUser().getNickName();
        Date date = DateUtils.parseDate(DateUtils.getTime());
        if(!IdCardUtil.check(pdsCompanyContact.getIdCard())){
            throw new Exception("身份证号不正确，请核实");
        }
        //要更新用户的userId
        Long userId = pdsCompanyContactMapper.getUserIdById(pdsCompanyContact.getId());

        //容错判断
        //判断用户表是否存在同手机号
        SysUser existUser = sysUserMapper.selectUserByUserName(pdsCompanyContact.getPhone());
        if (existUser != null && !String.valueOf(userId).equals(existUser.getUserId().toString())) {
            throw new Exception("修改失败，已存在相同手机号账户，请核实");
        }
        //判断本次修改是不是去掉了管理员权限，企业至于要有一个管理员账号
        List<Map> roles = sysRoleMapper.getAdminRoleByRoleKey(deptId, COMPANY_ADMIN_ROLE_KEY); //查询本企业当前所有的管理员
        if (roles.size() == 1) { //如果本企业当前只有一个管理员
            Map role = roles.get(0);
            if (String.valueOf(userId).equals(role.get("userId").toString())) { //如果要修改的用户就是唯一的管理员
                if (!pdsCompanyContact.getRoleIds().contains(role.get("roleId").toString())) {
                    throw new Exception("至少需要有一个管理员");
                }
                if (StringUtils.isNotEmpty(pdsCompanyContact.getStatus()) && !"0".equals(pdsCompanyContact.getStatus())) {
                    throw new Exception("至少需要有一个管理员");
                }
            }
        }

        //在pds_company_contact表中更新数据
        pdsCompanyContact.setUpdateBy(updateBy);
        pdsCompanyContact.setUpdateTime(date);
        pdsCompanyContactMapper.updateById(pdsCompanyContact);

        //在sys_user表中修改数据
        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setNickName(pdsCompanyContact.getName());
        user.setUserName(pdsCompanyContact.getPhone());
        user.setPhonenumber(pdsCompanyContact.getPhone());
        user.setSex(pdsCompanyContact.getSex());
        user.setStatus(pdsCompanyContact.getStatus());
        user.setUpdateBy(updateBy);
        user.setRemark(pdsCompanyContact.getRemark());
        sysUserMapper.updateUser(user);

        //在sys_user_role表中更新数据
        if (ObjectUtil.isNotEmpty(pdsCompanyContact.getRoleIds())) {
            //删除角色，重新保存
            sysUserRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            List<SysUserRole> userRoleList = new ArrayList<>();
            String[] roleIds = pdsCompanyContact.getRoleIds().split(",");
            for (String id : roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(Long.parseLong(id));
                userRoleList.add(userRole);
            }
            sysUserRoleMapper.batchUserRole(userRoleList);
        }
    }

    /**
     * 查询企业用户列表
     *
     * @param pdsCompanyContact - companyId 企业ID，环保局查询时需要传入
     *                          - name 姓名（查询条件）
     *                          - phone 联系方式（查询条件）
     *                          - idCard 身份证号（查询条件）
     * @return
     * @throws Exception
     */
    @Override
    public List<PdsCompanyContact> getCompanyUserList(PdsCompanyContact pdsCompanyContact) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysDept dept = sysUser.getDept();
        if ("2".equals(String.valueOf(dept.getType()))) {
            pdsCompanyContact.setCompanyId(dept.getOrganizationId());
        }
        return pdsCompanyContactMapper.getCompanyUserList(pdsCompanyContact);
    }

    /**
     * 查询企业用户详细
     *
     * @param id 主键id
     * @return
     * @throws Exception
     */
    @Override
    public PdsCompanyContact getUserInfo(Long id) {
        return pdsCompanyContactMapper.getCompanyUserInfo(id);
    }

    /**
     * 批量新增导入用户
     *
     * @param list
     * @param companyId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer importCompanyContact(List<CompanyContactExcel> list, Long companyId) throws Exception {
//        int total = 0;
//        Date date = DateUtils.parseDate(DateUtils.getTime());
//        for (CompanyContactExcel excel : list) {
//            PdsCompanyContact companyContact = new PdsCompanyContact();
//            BeanUtils.copyProperties(excel, companyContact);
//            companyContact.setStatus("1");
//            companyContact.setCreateTime(date);
//            companyContact.setCompanyId(companyId);
//            total += pdsCompanyContactMapper.insert(companyContact);
//        }

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        SysDept dept = sysUser.getDept();
        Date date = DateUtils.parseDate(DateUtils.getTime());

        for (int i = 0; i < list.size(); i++) {
            CompanyContactExcel data = list.get(i);

            SysUser existUser = sysUserMapper.selectUserByUserName(data.getPhone());
            if (existUser != null && "0".equals(existUser.getDelFlag())) {
                throw new Exception("导入失败，" + data.getPhone() + "已存在相同手机号账户，请核实");
            }

            //1.在pds_company_contact表中插入数据
            PdsCompanyContact pdsCompanyContact = new PdsCompanyContact();
            pdsCompanyContact.setCompanyId(dept.getOrganizationId());
            pdsCompanyContact.setName(data.getName());
            pdsCompanyContact.setPhone(data.getPhone());
            pdsCompanyContact.setStatus("0");
            pdsCompanyContact.setCreateBy(sysUser.getNickName());
            pdsCompanyContact.setCreateTime(date);
            pdsCompanyContactMapper.insert(pdsCompanyContact);

            //2.在sys_user表中插入数据
            SysUser user = new SysUser();
            user.setUserName(data.getPhone());
            user.setNickName(data.getName());
            String initPassword = sysConfigMapper.selectInitPassword();
            user.setPassword(SecurityUtils.encryptPassword(initPassword));
        }
        return list.size();
    }
}
